package com.uairobot.bill.tts.agent.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.jfinal.aop.Aop;
import com.uairobot.tts.client.biaobei.BiaoBeiClient;

/**
 * @author bill robot
 * @date 2020年1月16日_下午12:43:44 
 * @version 1.0 
 * @desc
 */
public class TTSService {

  private BiaoBeiClient bbc = Aop.get(BiaoBeiClient.class);

  @SuppressWarnings("unused")
  private String append(String symbol, Object... params) {
    StringBuffer strBuf = new StringBuffer();
    strBuf.append(params[0]);
    for (Integer i = 1; i < params.length; i++) {
      strBuf.append("_");
      strBuf.append(params[i]);
    }
    return strBuf.toString();
  }

  public String getFileName(String voice, String audioType, Integer rate, String md5Hex) {
    StringBuffer strBuf = new StringBuffer();
    strBuf.append(voice).append("_");
    strBuf.append(rate).append("_" );
    strBuf.append(md5Hex).append("." + audioType);
    return strBuf.toString();
  }

  public Map<String, Object> tts(String text, String voiceName, Integer audioType, Integer rate) {
    // 先合成,然后转为mp3格式
    Map<String, Object> tts = bbc.tts("ZH", voiceName, text, 5, 5, 5, audioType, rate);
    return tts;
  }

  public void ttsToFile(String filename, String text, String voiceName, Integer audioType, Integer rate) {
    Map<String, Object> ttsResult = bbc.tts("ZH", voiceName, text, 5, 5, 5, audioType, rate);
    ByteArrayOutputStream baos = null;
    if ("-1".equals(ttsResult.get("code"))) {
      return;
    } else {
      baos = (ByteArrayOutputStream) ttsResult.get("data");
    }
    try {
      File file = new File(filename);
      FileUtils.writeByteArrayToFile(file, baos.toByteArray());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
